<?php

/**
 * 密码加密方法
 * @param string $pw 要加密的字符串
 * @param string $authcode
 * @param $userName
 * @return string
 */
function sp_password($pw,$authcode='',$userName = ''){
    if(empty($authcode)){
        $authcode=C("AUTHCODE");
    }
    if($userName){
        $userName .= '_';
    }
    //$userName = '';
    $result=md5(md5($userName.$authcode.$pw));
    return $result;
}


/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $domain 是否显示域名
 * @return string
 */
function leuu($url='',$vars='',$suffix=true,$domain=false){
    //$routes=sp_get_routes();
    $routes=array();
    if(empty($routes)){
        return U($url,$vars,$suffix,$domain);
    }else{
        // 解析URL
        $info   =  parse_url($url);
        $url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
        if(isset($info['fragment'])) { // 解析锚点
            $anchor =   $info['fragment'];
            if(false !== strpos($anchor,'?')) { // 解析参数
                list($anchor,$info['query']) = explode('?',$anchor,2);
            }
            if(false !== strpos($anchor,'@')) { // 解析域名
                list($anchor,$host)    =   explode('@',$anchor, 2);
            }
        }elseif(false !== strpos($url,'@')) { // 解析域名
            list($url,$host)    =   explode('@',$info['path'], 2);
        }

        // 解析子域名
        //TODO?

        // 解析参数
        if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
            parse_str($vars,$vars);
        }elseif(!is_array($vars)){
            $vars = array();
        }
        if(isset($info['query'])) { // 解析地址里面参数 合并到vars
            parse_str($info['query'],$params);
            $vars = array_merge($params,$vars);
        }

        $vars_src=$vars;

        ksort($vars);

        // URL组装
        $depr       =   C('URL_PATHINFO_DEPR');
        $urlCase    =   C('URL_CASE_INSENSITIVE');
        if('/' != $depr) { // 安全替换
            $url    =   str_replace('/',$depr,$url);
        }
        // 解析模块、控制器和操作
        $url        =   trim($url,$depr);
        $path       =   explode($depr,$url);
        $var        =   array();
        $varModule      =   C('VAR_MODULE');
        $varController  =   C('VAR_CONTROLLER');
        $varAction      =   C('VAR_ACTION');
        $var[$varAction]       =   !empty($path)?array_pop($path):ACTION_NAME;
        $var[$varController]   =   !empty($path)?array_pop($path):CONTROLLER_NAME;
        if($maps = C('URL_ACTION_MAP')) {
            if(isset($maps[strtolower($var[$varController])])) {
                $maps    =   $maps[strtolower($var[$varController])];
                if($action = array_search(strtolower($var[$varAction]),$maps)){
                    $var[$varAction] = $action;
                }
            }
        }
        if($maps = C('URL_CONTROLLER_MAP')) {
            if($controller = array_search(strtolower($var[$varController]),$maps)){
                $var[$varController] = $controller;
            }
        }
        if($urlCase) {
            $var[$varController]   =   parse_name($var[$varController]);
        }
        $module =   '';

        if(!empty($path)) {
            $var[$varModule]    =   array_pop($path);
        }else{
            if(C('MULTI_MODULE')) {
                if(MODULE_NAME != C('DEFAULT_MODULE') || !C('MODULE_ALLOW_LIST')){
                    $var[$varModule]=   MODULE_NAME;
                }
            }
        }
        if($maps = C('URL_MODULE_MAP')) {
            if($_module = array_search(strtolower($var[$varModule]),$maps)){
                $var[$varModule] = $_module;
            }
        }
        if(isset($var[$varModule])){
            $module =   $var[$varModule];
        }

        if(C('URL_MODEL') == 0) { // 普通模式URL转换
            $url        =   __APP__.'?'.http_build_query(array_reverse($var));

            if($urlCase){
                $url    =   strtolower($url);
            }
            if(!empty($vars)) {
                $vars   =   http_build_query($vars);
                $url   .=   '&'.$vars;
            }
        }else{ // PATHINFO模式或者兼容URL模式

            if(empty($var[C('VAR_MODULE')])){
                $var[C('VAR_MODULE')]=MODULE_NAME;
            }

            $module_controller_action=strtolower(implode($depr,array_reverse($var)));

            $has_route=false;
            $original_url=$module_controller_action.(empty($vars)?"":"?").http_build_query($vars);

            if(isset($routes['static'][$original_url])){
                $has_route=true;
                $url=__APP__."/".$routes['static'][$original_url];
            }else{
                if(isset($routes['dynamic'][$module_controller_action])){
                    $urlrules=$routes['dynamic'][$module_controller_action];

                    $empty_query_urlrule=array();

                    foreach ($urlrules as $ur){
                        $intersect=array_intersect_assoc($ur['query'], $vars);
                        if($intersect){
                            $vars=array_diff_key($vars,$ur['query']);
                            $url= $ur['url'];
                            $has_route=true;
                            break;
                        }
                        if(empty($empty_query_urlrule) && empty($ur['query'])){
                            $empty_query_urlrule=$ur;
                        }
                    }

                    if(!empty($empty_query_urlrule)){
                        $has_route=true;
                        $url=$empty_query_urlrule['url'];
                    }

                    $new_vars=array_reverse($vars);
                    foreach ($new_vars as $key =>$value){
                        if(strpos($url, ":$key")!==false){
                            $url=str_replace(":$key", $value, $url);
                            unset($vars[$key]);
                        }
                    }
                    $url=str_replace(array("\d","$"), "", $url);

                    if($has_route){
                        if(!empty($vars)) { // 添加参数
                            foreach ($vars as $var => $val){
                                if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
                            }
                        }
                        $url =__APP__."/".$url ;
                    }
                }
            }

            $url=str_replace(array("^","$"), "", $url);

            if(!$has_route){
                $module =   defined('BIND_MODULE') ? '' : $module;
                $url    =   __APP__.'/'.implode($depr,array_reverse($var));

                if($urlCase){
                    $url    =   strtolower($url);
                }

                if(!empty($vars)) { // 添加参数
                    foreach ($vars as $var => $val){
                        if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
                    }
                }
            }


            if($suffix) {
                $suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
                if($pos = strpos($suffix, '|')){
                    $suffix = substr($suffix, 0, $pos);
                }
                if($suffix && '/' != substr($url,-1)){
                    $url  .=  '.'.ltrim($suffix,'.');
                }
            }
        }

        if(isset($anchor)){
            $url  .= '#'.$anchor;
        }
        if($domain) {
            $url   =  (is_ssl()?'https://':'http://').$domain.$url;
        }

        return $url;
    }
}

//处理无限子分类
function make_tree($list,$pk='id',$pid='pid',$child='_child',$root=0){
    $tree=array();
    $packData=array();
    foreach ($list as  $data) {
        $packData[$data[$pk]] = $data; //$packData[1]=$data; $packData[2]=$data
    }
    foreach ($packData as $key =>$val){
        if($val[$pid]==$root){   //代表跟节点
            $tree[]=& $packData[$key];
        }else{
            //找到其父类
            $packData[$val[$pid]][$child][]=& $packData[$key];
        }
    }
    return $tree;
}

/**
 * 图片缩放
 * @param string $imagePath 图片路径
 * @param string $thumbPath 压缩后的图片路径
 * @param int $w 宽度
 * @param int $h 高度
 * @return string 返回路径
 */
function resizeImage($imagePath, $thumbPath, $w = 160, $h = 160)
{
    $savepath = $thumbPath;

    //获取图片的基本信息
    $info = getimagesize($imagePath);
    $width =  $info[0];//获取图片宽度
    $height = $info[1];//获取图片高度
    $per1 = round($width/$height,2);//计算原图长宽比
    $per2 = round($w/$h,2);//计算缩略图长宽比
    $per = null;

    //计算缩放比例
    if($per1>$per2||$per1==$per2)
    {
        //原图长宽比大于或者等于缩略图长宽比，则按照宽度优先
        $per = $w/$width;
    }
    if($per1<$per2)
    {
        //原图长宽比小于缩略图长宽比，则按照高度优先
        $per = $h/$height;
    }
    $temp_w = intval($width*$per);//计算原图缩放后的宽度
    $temp_h = intval($height*$per);//计算原图缩放后的高度
    $temp_img = imagecreatetruecolor($temp_w,$temp_h);//创建画布
    $im = createImage($imagePath);
    imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);
    if($per1>$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return imageAddBg($savepath,$w,$h,"w");
        //宽度优先，在缩放之后高度不足的情况下补上背景
    }
    if($per1==$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return $savepath;
        //等比缩放
    }
    if($per1<$per2)
    {
        imagejpeg($temp_img,$savepath, 100);
        imagedestroy($im);
        return imageAddBg($savepath,$w,$h,"h");
        //高度优先，在缩放之后宽度不足的情况下补上背景
    }
}

/**
 * 创建图片，返回资源类型
 * @param string $src 图片路径
 * @return resource $im 返回资源类型
 * **/
function createImage($src) {
    $im = null;
    $info=getimagesize($src);
    switch ($info[2])
    {
        case 1:
            $im=imagecreatefromgif($src);
            break;
        case 2:
            $im=imagecreatefromjpeg($src);
            break;
        case 3:
            $im=imagecreatefrompng($src);
            break;
    }
    return $im;
}

/**
 * 添加背景
 * @param string $src 图片路径
 * @param int $w 背景图像宽度
 * @param int $h 背景图像高度
 * @param string $fisrt 决定图像最终位置的，w 宽度优先 h 高度优先 wh:等比
 * @return string 返回加上背景的图片
 */
function imageAddBg($src,$w,$h,$fisrt ="w") {
    $bg=imagecreatetruecolor($w,$h);
    $white = imagecolorallocate($bg,255,255,255);
    imagefill($bg,0,0,$white);//填充背景

    //获取目标图片信息
    $info=getimagesize($src);
    $width=$info[0];//目标图片宽度
    $height=$info[1];//目标图片高度
    $img=createImage($src);
    if($fisrt=="wh")
    {
        //等比缩放
        return $src;
    }
    else
    {
        if($fisrt=="w")
        {
            $x=0;
            $y=($h-$height)/2;//垂直居中
        }
        if($fisrt=="h")
        {
            $x=($w-$width)/2;//水平居中
            $y=0;
        }
        imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
        imagejpeg($bg,$src,100);
        imagedestroy($bg);
        imagedestroy($img);
        return $src;
    }
}

/**
 * 对称加密算法之加密
 * @param String $string 需要加密的字串
 * @date 2015-08-13 19:30
 * @return String
 */
function encode($string = '') {
    $skey = C("AUTHCODE");
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key].=$value;
    return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}

/**
 * 发送短信
 * @param $PhoneNo string 手机号码
 * @param $content string
 * @param $ALY_TemplateCode string 短信模板编号
 * @param $type
 * @return string
 * @throws \Think\Exception
 */
function sendSMS($PhoneNo, $content, $ALY_TemplateCode,$type) {

    require_once './Application/Common/Lib/Aliyun/new/SMSHelper.class.php';
    $ALY_accessKey = 'LTAICJlzpsPecIln';
    $ALY_accessSecret = 'OhMXA1lJakkyIbuhHXbV807KBiWtQG';
    $ALY_SignName = '传奇蓝莓';

    if($ALY_accessKey && $ALY_accessSecret && $ALY_SignName && $ALY_TemplateCode){
        $sms = new \SMSHelper($ALY_accessKey,$ALY_accessSecret);

        $response = $sms->sendSms(
            $ALY_SignName, // 短信签名
            $ALY_TemplateCode, // 短信模板编号
            $PhoneNo, // 短信接收者
            $content
        );
        $smsData['Mobile'] = $PhoneNo;
        $smsData['Content'] = json_encode($content,JSON_UNESCAPED_UNICODE);
        $smsData['SMSType'] = $type;
        $smsData['SendTime'] = date('Y-m-d H:i:s');

        switch($response->Code){
            case 'OK':{
                $smsData['SendState'] = 0;//成功
            }break;
            default:{
                $smsData['SendState'] = 1;//失败
            }
        }
        //M('Smslog')->add($smsData);

        return $response;
    }else{
        throw new \Think\Exception('短信参数错误');
    }
}


/** 目录创建 
* @param  String $path  路径 
* @param  String $id 需要关联的ID 
* @return array 
*/
function createdirlist($path){
    $mode=0777;  
    if (is_dir($path)){
        //判断目录存在否，存在不创建
        return true;
        //已经存在则输入路径
    }else{
      //不存在则创建目录
      $re=mkdir($path,$mode,true);               
      if ($re){
        return true;
      }else{
        return false;
      }
    }
}

/*
* 发送消息方法
* $GUID  string 1,2,3,4 逗号分隔的用户ID
* $Content  string 发送的内容 
*/
function send_messag($GUID='',$title='',$Content=''){
    $GUID = explode(',', $GUID);
    if(empty($GUID)){
      return false;
    }
    $MessageModel = M("Message");
    $data['SUID']  = session('USER_ID');
    $data['SendTime']  = date('Y-m-d H:i:s');
    $data['Title']  = $title;
    $data['Content'] = htmlspecialchars_decode($Content);
    $result = $MessageModel->add($data);
    if($result){
        $data = array();
        foreach ($GUID as $key => $val) {
            $data['GUID'] = $val;
            $data['MID'] = $result;
            $data['OpenTime'] = null;
            M('message_user_rel')->add($data);
        }
        return true;
    }else{
        return false;
    }  
}